package com.xmread.cn.network;

import android.os.Handler;
import android.util.Log;
import com.liuguang.framework.utils.AppUtils;
import com.liuguang.framework.utils.StringUtils;
import com.xmread.cn.config.AppConfig;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Interceptor.Chain;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit.Builder;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;

public class RetrofitManager {
    public static final String BASE_URL = AppConfig.baseUrl;
    public static final String CACHE_CONTROL_AGE = "Cache-Control: public, max-age=";
    public static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=604800";
    public static final String CACHE_CONTROL_NETWORK = "max-age=0";
    public static final int CACHE_STALE_LONG = 604800;
    public static final int CACHE_STALE_SHORT = 60;
    public static final String HEADER_CONTENT_TYPE = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8";
    private static OkHttpClient mOkHttpClient;
    private static RetrofitManager mRetrofitManager;
    private Handler handler = null;
    private Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
        public Response intercept(Chain chain) throws IOException {
            Request request;
            Request request2 = chain.request();
            String token = "";//BookCacheUtil.getToken();
            if (StringUtils.isBlank(token)) {
                token = "";
            }
            if (!RFNetUtil.isNetworkConnected()) {
                request = request2.newBuilder().addHeader("token", "")
                        .addHeader("app_id", String.valueOf(AppConfig.BOOK_APPID))
                        .addHeader("version", AppUtils.getAppVersion())
                        .addHeader("system", String.valueOf(2))
                        .cacheControl(CacheControl.FORCE_CACHE).build();
            } else {
                request = request2.newBuilder().addHeader("token", token)
                        .addHeader("app_id", String.valueOf(AppConfig.BOOK_APPID))
                        .addHeader("version", AppUtils.getAppVersion())
                        .addHeader("system", String.valueOf(2)).build();
            }
            Log.d("request ----------> ", request.url().toString());
            Response proceed = chain.proceed(request);
            StringBuilder sb = new StringBuilder();
            sb.append(proceed);
            sb.append("");
            Log.d("response ----------> ", sb.toString());
            if (!RFNetUtil.isNetworkConnected()) {
                return proceed.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=604800")
                        .removeHeader("Pragma").build();
            }
            return proceed.newBuilder().header("Cache-Control", request.cacheControl().toString()).removeHeader("Pragma").build();
        }
    };
    public final BookService service;

    public static RetrofitManager builder() {
        RetrofitManager retrofitManager;
        if (mRetrofitManager != null) {
            return mRetrofitManager;
        }
        synchronized (RetrofitManager.class) {
            if (mRetrofitManager == null) {
                mRetrofitManager = new RetrofitManager();
            }
            retrofitManager = mRetrofitManager;
        }
        return retrofitManager;
    }

    public static BookService getDefault() {
        return builder().service;
    }

    protected RetrofitManager() {
        initOkHttpClient();
        this.service = (BookService) new Builder().baseUrl(BASE_URL).client(mOkHttpClient)
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create()).build().create(BookService.class);
    }

    private void initOkHttpClient() {
        new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
        if (mOkHttpClient == null) {
            synchronized (RetrofitManager.class) {
                if (mOkHttpClient == null) {
                    mOkHttpClient = new OkHttpClient.Builder().cache(new Cache(new File(AppUtils.getApplication().getCacheDir(), "HttpCache"), 104857600))
                            .addInterceptor(this.mRewriteCacheControlInterceptor).retryOnConnectionFailure(true)
                            .sslSocketFactory(SSLFactoryManager.getDefaultTrust())
                            .hostnameVerifier(SSLFactoryManager.getDefaultHostnameVerifierTrust())
                            .connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS)
                            .writeTimeout(60, TimeUnit.SECONDS).build();
                }
            }
        }
    }
}
